package com.eco.common.handler;


import com.eco.common.constant.BizErrorCodeEnum;
import com.eco.common.response.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

@ControllerAdvice
public class WebExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(WebExceptionHandler.class);

    public WebExceptionHandler() {
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseBody
    public BaseResponse MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String message = (String) e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining());
        BaseResponse<String> response = new BaseResponse<>();
        response.setMsgCode(BizErrorCodeEnum.SYSTEM_ERROR.getCode());
        response.setMsg(message);
        return response;
    }


    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public BaseResponse<String> handleException(RuntimeException e) {
        log.error("系统异常信息：RuntimeException:{}, error:{}", e, e.getMessage());
        BaseResponse<String> response = new BaseResponse<>();
        response.setMsgCode(BizErrorCodeEnum.SYSTEM_ERROR.getCode());
        response.setMsg(e.getMessage());
        return response;
    }
}
